import re
import os
import subprocess

old_version = '5.28.4+dfsg1+~cs23.12.11-2'
new_version = '5.28.4+dfsg1+~cs23.12.11-2ok1'

filenames = os.listdir()
for filename in filenames:
    # 处理deb包
    if re.search(r'\.deb$', filename):
        print(filename)
        filename_list = filename.split('_')
        arch = filename_list[2].split('.')[0]
        new_dirname = filename_list[0] + '_' + new_version + '_' + arch
        print(filename_list)
        result = subprocess.run(['dpkg-deb', '-x', filename, new_dirname], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        if result.returncode != 0:
            raise Exception(result.stderr)
        result = subprocess.run(['dpkg-deb', '-e', filename, new_dirname + '/DEBIAN'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        if result.returncode != 0:
            raise Exception(result.stderr)

        control_name = new_dirname + '/DEBIAN' + '/control'
        with open(control_name) as control:
            lines = control.readlines()
            for i in range(len(lines)):
                lines[i] = re.sub(re.escape(old_version), new_version, lines[i])
        with open(control_name, 'w') as control:
            control.writelines(lines)

        result = subprocess.run(['dpkg-deb', '--build',  new_dirname], stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, text=True)
        if result.returncode != 0:
            raise Exception(result.stderr)

        result = subprocess.run(['rm', '-rf', new_dirname, filename], stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, text=True)
        if result.returncode != 0:
            raise Exception(result.stderr)

    # 处理changes文件
    # TODO